from flask import Flask, request, render_template
import json
import base64
import urllib.parse
import requests
app = Flask(__name__)
def logs(req, res = None):
    with open("requests_log.log", "a") as f:
        print(req.form, req.host_url, req.remote_addr, file=f, sep="|")

@app.route("/", methods=["get"])
def index():
    logs(request)
    return render_template("index.html")

@app.route("/plant", methods=["get"])
def plant():
    logs(request)
    return render_template("plant.html")

@app.route("/air", methods=["get"])
def air():
    logs(request)
    return render_template("airs.html")

@app.route("/texts", methods=["get"])
def texts():
    logs(request)
    return render_template("texts.html")

@app.route("/view", methods=["get"])
def view():
    logs(request)
    return render_template("view.html")

@app.route("/plantdata", methods=["get"])
def plantdata():
    api_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
    urls = request.args.get("url")

    rep = requests.get(urls).content
    img = base64.b64encode(rep)
    params = {"image": img}
    logs(request, params)
    data = urllib.parse.urlencode(params)
    access_token = '[24.b9f329c3865e8b2340f89234de6dcafc.2592000.1612459441.282335-23492501]'
    post_params = {"access_token": access_token}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    rep = requests.post(api_url, headers=headers, data=data, params=post_params)
    lis = json.loads(rep.text)["result"]
    max_score = float(lis[0]["score"])
    names = ""
    for data in lis:
        if float(data["score"]) > max_score:
            max_score = data["score"]
            names = data["name"]
        else:
            names = lis[0]["name"]
    return {"name": names, "imgbase64": img.decode()}

@app.route("/airdata", methods=["get"])
def airdata():
    url = "https://devapi.qweather.com/v7/air/now"
    city = request.args.get("city")
    logs(request, res = city)
    key = "e148e8e77bad4eba98a5b52a695235fa"
    params = {
        "location": city,
        "key": key
    }
    city_rep = requests.get("https://geoapi.qweather.com/v2/city/lookup", params=params)
    city_id = json.loads(city_rep.text)["location"][0]["id"]
    params = {
        "location": city_id,
        "key": key
    }
    rep = requests.get(url, params=params)
    return json.loads(rep.text)

@app.route("/textdata", methods=["get"])
def textdata():
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    urls = request.args.get("img")
    logs(request, urls)
    rep = requests.get(urls).content
    img = base64.b64encode(rep)
    params = {"image": img}
    data = urllib.parse.urlencode(params)
    access_token = '[24.1c7176467c0409c0d446b2f1085a37e4.2592000.1612465625.282335-23492537]'
    post_params = {"access_token": access_token}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    rep = requests.post(url, headers=headers, data=data, params=post_params)
    print(rep.text)
    datas = json.loads(rep.text)
    values = ""
    try:
        for data in datas["words_result"]:
            values += data["words"]
    except:
        return {"values": "查找失败，暂时无法识别"}
    return {"values":values, "imgbase64": img.decode()}

@app.route("/viewlog", methods=["GET"])
def viewlog():
    with open("requests_log.log", "r") as f:
        contents = []
        for data in f:
            splits = data.split("|")
            contents.append({"Formdata" : splits[0], "Host_url": splits[1], "Remote_addr": splits[2]})
    return {"content": contents}

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

